package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;

@Slf4j
public class LoginInterceptor1 implements HandlerInterceptor {
    StringRedisTemplate stringRedisTemplate;

    public LoginInterceptor1(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate=stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入拦截器");
        String token = request.getHeader("authorization");

        log.info("token 是"+token);
        System.out.println(token);

        if(token==null){
            return true;
        }
        String token1 = LOGIN_USER_KEY + token;
//        TODO 2、从TOKEN中获取用户对象
        Map<Object, Object> UserMap = stringRedisTemplate.opsForHash().entries(token1);
        if(UserMap.isEmpty()){
            return true;
        }
//        TODO 3、将对象转换为DTO对象，原本是Map类型
        UserDTO userDTO = BeanUtil.fillBeanWithMap(UserMap, new UserDTO(), false);
//        TODO 4、将对象放入ThreadLocal中
        UserHolder.saveUser(userDTO);
        log.info(userDTO.toString());
        stringRedisTemplate.expire(token1,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        return true;


    }
}
